
<template>
  <div class="app-container">
    <div class="filter-container">
      <filter-form :i-org-options="options" />
      <!-- <el-button type="primary" @click="dialogPvVisible = true">添加</el-button> -->
      <!-- <el-button type="danger">删除</el-button> -->
    </div>
    <el-table v-loading="loading" :data="tableData" style="width: 100%" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column prop="strDevicename" label="设备名称" width="180" />
      <el-table-column prop="strValue" label="设备类型" width="80" />
      <el-table-column prop="strDevicenum" label="设备序列号" />
      <el-table-column prop="strGrantdevicenum" label="设备码" width="80" />
      <el-table-column prop="strOrgname" label="所属机构" width="140" />
      <el-table-column prop="strValue1" label="设备状态" width="140" />
      <el-table-column label="操作" min-width="180">
        <template slot-scope="{row,$index}">
          <el-button
            size="mini"
            type="primary"
            @click="handleModifyStatus(row)"
          >{{ row.iStatus === 3 ? '配置': '修改' }}</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-show="total>0"
      :total="total"
      :page.sync="pagenum"
      :limit.sync="limit"
      :layout="layout"
      @pagination="fetchList"
    />

    <el-dialog
      :visible.sync="dialogPvVisible"
      width="612px"
      :append-to-body="true"
      :title="dialogTitle"
      :close-on-click-modal="false"
    >
      <div>
        <el-form
          ref="ruleForm"
          :model="form"
          :rules="rules"
          label-position="left"
          label-width="100px"
          :inline="true"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item prop="strDevicename" label="设备名称">
                <el-input v-model="form.strDevicename" placeholder="请输入设备名称" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item prop="iDevicetype" label="设备类型">
                <el-select v-model="form.iDevicetype" placeholder="请选择设备类型">
                  <el-option
                    v-for="item in optionsType"
                    :key="item.id"
                    :label="item.strValue"
                    :value="item.strCode"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item prop="iOrgsysnum" label="所属机构">
                <el-cascader
                  v-model="form.iOrgsysnum"
                  :show-all-levels="false"
                  :options="options"
                  :props="{ expandTrigger: 'hover',value:'strOrgnum',label:'strOrgname',children: 'yhlist', checkStrictly: true }"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="默认应用">
                <el-input v-model="defaultApp" class="inptw200" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="strDevicenum" label="设备序列号">
                <el-input v-model="form.strDevicenum" class="inptw200" disabled placeholder="请输入设备序列号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="strGrantdevicenum" label="设备码">
                <el-input v-model="form.strGrantdevicenum " class="inptw200" placeholder="请输入设备码" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button v-if="editStatus" type="primary" @click="handleConfirm">确 认</el-button>
        <el-button v-else type="primary" @click="updateDevices">修 改</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>

import {
  // getDeviceList,
  addDeviceInfo,
  deleteDeviceInfo,
  getDetaultapp,
  getDeviceType,
  getOrglist

} from '@/api/addTag'
import Pagination from '@/components/Pagination'
import pages from '@/mixins/pages'
import { validateValue, validateNumber } from '@/utils/validateForm'
import { updatesDevData, beforeList, mqsend } from '@/api/devices/index'
import FilterForm from './componts/filterForm'

export default {
  name: 'TerminalList',
  components: { Pagination, FilterForm },
  mixins: [pages],
  props: {},
  data() {
    return {
      loading: false,
      dialogPvVisible: false,
      strOrgnum: [],
      defaultApp: '',
      total: 0,
      limit: 5,
      pagenum: 1,
      currentpage: 1,
      layout: 'total, prev, pager, next, jumper',
      form: {
        strDevicename: '',
        iDevicetype: '',
        strGrantdevicenum: '',
        iOrgsysnums: this.$store.getters.iOrgsysnum,
        iOrgsysnum: ''
      },
      dialogTitle: '新增终端',
      optionsType: [],
      options: [],
      tableData: [],
      editStatus: true, // true新增 false编辑,
      rules: {
        strDevicename: [
          {
            required: true,
            message: '请输入设备名称',
            validator: validateValue,
            trigger: 'blur'
          }
        ],
        iDevicetype: [
          { required: true, message: '请选择设备类型', trigger: 'change' }
        ],
        iOrgsysnum: [
          { required: true, message: '请选择所属机构', trigger: 'change' }
        ],
        strGrantdevicenum: [
          { required: true, trigger: 'blur', validator: validateNumber }
        ]
      }
    }
  },
  created() {
    this.fetchAppList()
    this.fetchList()
  },
  mounted() {},
  methods: {
    fetchList() {
      // type 类型（1，所有设备，2，已部署设备）
      // getDeviceList({ pagenum: this.pagenum, iOrgsysnums: this.$store.getters.iOrgsysnum, type: 1 }).then(res => {
      //   this.tableData = res.data
      //   this.total = !res.total ? 0 : res.total
      //   this.currentpage = res.currentpage
      // })
      mqsend({ pagenum: this.pagenum, iOrgsysnums: this.$store.getters.iOrgsysnum, type: 1 })
      this.loading = true
      setTimeout(() => {
        beforeList({ pagenum: this.pagenum, iOrgsysnums: this.$store.getters.iOrgsysnum, type: 1 }).then(res => {
          this.tableData = res.data
          this.total = !res.total ? 0 : res.total
          this.currentpage = res.currentpage
          this.loading = false
        }).catch(err => {
          console.log(err)
        })
      }, 3000)
    },

    handleDelete(row, index) {
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteDeviceInfo({ iDevicesysnum: row.iDevicesysnum }).then(res => {
            // console.log(res);
            this.$message({
              title: '提示',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.ResetCurrentPage()
            this.fetchList()
          })
        })
        .catch(err => {
          console.error(err)
        })
    },
    handleConfirm() {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          this.addDevices()
          this.$refs['ruleForm'].resetFields()
          this.dialogPvVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleCancel() {
      this.strOrgnum = []
      this.$refs['ruleForm'].resetFields()
      this.dialogPvVisible = false
      this.form = {
        strDevicename: '',
        iDevicetype: '',
        iOrgsysnum: []
      }
      this.dialogTitle = '新增终端'
    },

    fetchAppList() {
      getDetaultapp({ iDevicetype: 1 }).then(res => {
        const arr = []
        res.data.map(item => {
          arr.push(item.jcappname)
        })
        this.defaultApp = arr.join()
      })
      getDeviceType({ type: 7 }).then(res => {
        // console.log(res)
        this.optionsType = res.data
      })
      getOrglist().then(res => {
        // console.log(res)
        this.options = res.data
      })
    },
    addDevices() {
      this.form.iOrgsysnum = this.form.iOrgsysnum.splice(-1)[0]
      this.form.iStatus = 3
      addDeviceInfo(this.form).then(res => {
        this.fetchList()
      })
    },
    handleModifyStatus(row) {
      this.editStatus = false
      this.dialogTitle = row.iStatus === 3 ? '配置终端' : '修改终端'
      // this.form = row
      this.form.strGrantdevicenum = row.strGrantdevicenum
      this.form.strDevicenum = row.strDevicenum
      this.form.strDevicename = row.strDevicename
      this.form.iDevicetype = row.iDevicetype
      this.form.iDevicesysnum = row.iDevicesysnum
      this.form.iOrgsysnum = row.iOrgsysnum.toString()
      this.form.iDevicetype = this.form.iDevicetype.toString()
      this.form.iStatus = row.iStatus
      this.form.id = row.id
      this.dialogPvVisible = true
    },
    updateDevices() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          let iOrgsysnum = ''
          if (this.form.iOrgsysnum instanceof Array) {
            iOrgsysnum = this.form.iOrgsysnum.splice(-1)[0]
          } else {
            iOrgsysnum = this.form.iOrgsysnum
          }
          const listQuery = {
            strGrantdevicenum: this.form.strGrantdevicenum,
            iOrgsysnum,
            strDevicename: this.form.strDevicename,
            iDevicetype: this.form.iDevicetype,
            strDevicenum: this.form.strDevicenum,
            iDevicesysnum: this.form.iDevicesysnum,
            id: this.form.id
          }
          updatesDevData(listQuery).then(res => {
            this.$message({
              type: 'success',
              message: '修改成功'
            })
            this.fetchList()
          })
          this.dialogPvVisible = false
          this.editStatus = true
          this.strOrgnum = []
          this.$refs['ruleForm'].resetFields()
          this.form.strDevicename = ''
          this.form.iDevicetype = ''
          this.form.iOrgsysnum = ''
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.marginTop {
  margin-top: 20px;
}
.title {
  margin: 30px 0;
}
</style>
